﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Menu;
using B.S.BasicData.Read.DTOS;
using MediatR;
using NLog.Time;

namespace B.S.BasicData.Read.Apilication.Handler.Menu
{
    public class GetmenuHandler : IRequestHandler<GetmenuCommon, ApiPaimg<MenuDTO>>
    {
        private readonly IBaseRepository<menuModel> menuRepo;
        private readonly IBaseRepository<UserModel> userRepo;

        public GetmenuHandler(IBaseRepository<menuModel> menuRepo,IBaseRepository<UserModel> userRepo)
        {
            this.menuRepo = menuRepo;
            this.userRepo = userRepo;
        }



        public Task<ApiPaimg<MenuDTO>> Handle(GetmenuCommon request, CancellationToken cancellationToken)
        {
            ApiPaimg<MenuDTO> res = new ApiPaimg<MenuDTO>();

            var menuinfo = menuRepo.GetAll().Where(x => x.IsDeleted == false);

          

            var linq = from a in menuinfo
                       join b in menuinfo.DefaultIfEmpty()//左连接，处理顶级菜单
                       on a.ParentId equals b.MenuId
                       into parentGroup
                       from b in parentGroup.DefaultIfEmpty()//确保左连接语义
                       select new MenuDTO
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           MenuUrl = a.MenuUrl,
                           ParentId = a.ParentId,
                           ParentNsme=b.MenuName,
                           CreateBy = a.CreateBy,
                           CreateDate = a.CreateDate,
                           UpdateBy = a.UpdateBy,
                           UpdateDate = a.UpdateDate,
                           IsDeleted = a.IsDeleted,
                       };

            
            res.ToTaCount= linq.Count();
            res.ToTaPage = (int) Math.Ceiling(res.ToTaCount*1.0/request.PageSize);
            res.PageData = linq.OrderByDescending(x=>x.MenuId).Skip((request.pageindex-1)*request.PageSize).Take(request.PageSize).ToList();
            res.Message = "菜单列表显示成功";
              return Task.FromResult(res);    
        }
    }  
    }

